/*
@Time : 2019/2/27 0027 11:06
@Author : visons
*/
package redis_svc

import (
	"fmt"
	"gitee.com/visons/gopkg/logger"
	"github.com/go-redis/redis"
	"sync"
	"time"
	"web-model/config"
)

type sRedis struct {
	client *redis.Client
}

var redisInstance *sRedis
var instanceOnce sync.Once

func NewRedisInstance() *sRedis {
	instanceOnce.Do(func() {
		redisInstance = &sRedis{
			client: &redis.Client{},
		}
		redisInstance.Init()
	})
	return redisInstance
}

func (r *sRedis) Init() bool {
	config := config.GetConfig().Redis
	client := redis.NewClient(&redis.Options{
		Network:      config.Network,
		Addr:         config.Addr,
		Password:     config.Password,
		DB:           config.DB,
		MaxRetries:   1,
		DialTimeout:  time.Duration(config.DialTimeout) * time.Second,
		ReadTimeout:  time.Duration(config.ReadTimeout) * time.Second,
		WriteTimeout: time.Duration(config.WriteTimeout) * time.Second,
		PoolSize:     config.PoolSize,
	})
	val, err := client.Ping().Result()
	if err != nil || val != "PONG" {
		logger.Painc("redis  %v init failed:%v", config, err)
	}

	fmt.Println("连接池：", client.PoolStats().IdleConns)
	r.client = client
	return true
}

func (r *sRedis) Shut() bool {
	r.client.Close()
	return true
}

func GetClient() *redis.Client {
	return redisInstance.client
}
